<!-- 聊天窗口 -->
<template>
  <div class="chat-window">
    <header class="chat-header">
      <img src="../assets/icons/back.svg" class="back-button" @click="goBack" alt="返回" />
      <h2 class="chat-title">{{ userName }}</h2>
    </header>
    <div class="chat-messages" 
         ref="messagesContainer"
         @scroll="handleScroll">
      <div v-if="isLoading" class="loading-indicator">
        加载中...
      </div>
      <div 
        v-for="message in chatMessages" 
        :key="message.messageId"
        :class="['message', message.senderId === currentUserId ? 'mine' : '']"
      >
        <div class="message-content">{{ message.content }}</div>
        <div class="message-time">{{ formatTime(message.sentAt) }}</div>
      </div>
    </div>
    <div class="chat-input">
      <input 
        v-model="newMessage" 
        @keyup.enter="sendMessage" 
        placeholder="输入消息..."
      />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { wsService } from '../utils/websocket';
import userImage from '../assets/1.svg';
import { chatStorage } from '../utils/chatStorage';

// 移除测试用户数据
// const testUsers = {
//   1: { name: '我', avatar: userImage },
//   2: { name: '客服小王', avatar: userImage },
//   3: { name: '快递员小李', avatar: userImage }
// }

const route = useRoute()
const router = useRouter()
const conversationId = Number(route.params.id)
const userName = ref(route.query.userName || '加载中...') // 从查询参数中获取 userName
const currentUserId = 1 // 模拟当前用户ID
const messagesContainer = ref(null)

// 聊天信息
const chatInfo = ref({
  userName: userName.value,
  conversationId: conversationId
})

// 修改 loadChatInfo 函数
const loadChatInfo = async () => {
  // 使用传递的 userName 而不是硬编码的 otherUserId
  chatInfo.value = {
    userName: userName.value,
    conversationId: conversationId
  }

  // 如果需要其他用户信息，可以根据实际需求进行获取
  // 例如，通过 conversationId 获取 otherUserId 并设置
  // const otherUserId = await getOtherUserId(conversationId);
  // chatInfo.value.otherUserId = otherUserId;
}

// 消息列表
const chatMessages = ref([])
const newMessage = ref('')

// 添加加载状态和分页控制
const isLoading = ref(false);
const hasMoreMessages = ref(true);
const currentPage = ref(0);
const pageSize = 20;

// 优化消息加载
const loadMessages = async () => {
  try {
    isLoading.value = true;
    const options = {
      limit: pageSize,
      offset: currentPage.value * pageSize
    };
    
    const messages = chatStorage.getConversationMessages(conversationId, options);
    if (messages.length < pageSize) {
      hasMoreMessages.value = false;
    }
    
    // 修改消息添加顺序
    chatMessages.value = [...chatMessages.value, ...messages];
    currentPage.value++;
  } catch (error) {
    console.error('加载消息失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 添加下拉加载更多
const handleScroll = async (event) => {
  const { scrollTop } = event.target;
  if (scrollTop === 0 && !isLoading.value && hasMoreMessages.value) {
    await loadMessages();
  }
};

// 优化发送消息
const sendMessage = async () => {
  if (newMessage.value.trim() === '') return;

  const message = {
    type: 'chat_message',
    conversationId: conversationId,
    content: newMessage.value,
    senderId: currentUserId,
    sentAt: new Date().toISOString(),
    status: 'sending'
  };

  try {
    // 先发送消息
    await wsService.send(message);
    // 清空输入框
    newMessage.value = '';
    // 不需要手动添加消息到列表，因为 WebSocket 的回调会处理这个
  } catch (error) {
    console.error('发送消息失败:', error);
    message.status = 'failed';
  }
};

// 从本地存储加载消息
const loadMessagesOld = async () => {
  try {
    // 1. 从本地存储加载历史消息
    const localMessages = chatStorage.getConversationMessages(conversationId);
    if (localMessages.length > 0) {
      chatMessages.value = localMessages;
      scrollToBottom();
    }

    // 2. 尝试从服务器加载更新的消息
    const lastMessage = localMessages[localMessages.length - 1];
    const lastTime = lastMessage ? lastMessage.sentAt : null;

    const params = {
      limit: 20,
      before: new Date(),
      after: lastTime
    };

    // 开发环境使用模拟数据
    if (process.env.NODE_ENV === 'development') {
      // 如果本地没有消息，添加一些测试消息
      if (localMessages.length === 0) {
        const mockMessages = [
          {
            messageId: Date.now() - 2000,
            conversationId,
            senderId: 2,
            content: '您好，需要什么帮助？',
            sentAt: new Date(Date.now() - 3600000).toISOString()
          },
          {
            messageId: Date.now() - 1000,
            conversationId,
            senderId: 1,
            content: '我想问一下快递的事情',
            sentAt: new Date(Date.now() - 1800000).toISOString()
          }
        ];
        mockMessages.forEach(msg => chatStorage.addMessage(msg));
        chatMessages.value = mockMessages;
      }
    } else {
      // 真实环境从服务器获取新消息
      // const serverMessages = await fetchMessages(conversationId, params);
      // const mergedMessages = mergeMessages(chatMessages.value, serverMessages);
      // chatMessages.value = mergedMessages;
    }

    scrollToBottom();
  } catch (error) {
    console.error('加载消息失败:', error);
  }
}

// 保存消息到本地存储
const saveMessages = () => {
  localStorage.setItem(`messages_${conversationId}`, JSON.stringify(chatMessages.value))
}

const sendMessageOld = () => {
  if (newMessage.value.trim() === '') return

  const message = {
    type: 'chat_message',
    conversationId: conversationId,
    content: newMessage.value,
    senderId: currentUserId,
    sentAt: new Date().toISOString()
  };

  // 保存到本地存储
  const savedMessage = chatStorage.addMessage(message);
  
  // 通过 WebSocket 发送消息
  wsService.send(savedMessage);

  // 更新UI
  chatMessages.value.push(savedMessage);
  newMessage.value = '';
  scrollToBottom();
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const formatTime = (timeString) => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 标记消息为已读
const markMessagesAsRead = () => {
  const markedCount = chatStorage.markConversationAsRead(conversationId, currentUserId);
  if (markedCount > 0) {
    // 可以在这里触发一些更新，比如通知其他组件更新未读计数
    console.log(`${markedCount} 条消息已标记为已读`);
  }
}

// 模拟消息已读状态
const markMessageAsRead = (messageId) => {
  // TODO: 后端集成时替换为实际 API 调用
  // await fetch(`/api/messages/${messageId}/read`, { method: 'POST' });
  
  const readStatus = JSON.parse(localStorage.getItem('messageReadStatus') || '[]');
  readStatus.push({
    messageId,
    userId: currentUserId,
    readAt: new Date().toISOString()
  });
  localStorage.setItem('messageReadStatus', JSON.stringify(readStatus));
}

const goBack = () => {
  router.push({ 
    name: 'ChatList',
    // 保留在主布局中的 message 路径
    path: '/message'
  })
}

// 定义页面可见性变化处理函数
const handleVisibilityChange = () => {
  if (document.visibilityState === 'visible') {
    markMessagesAsRead();
  }
};

// 定义消息处理函数
const handleNewMessage = (message) => {
  if (message.type === 'chat_message' && message.conversationId === conversationId) {
    // 添加消息到列表
    chatMessages.value.push(message);
    scrollToBottom();
  }
};

onMounted(async () => {
  await loadChatInfo();
  await loadMessages();
  
  // 只标记已加载的消息为已读
  const existingMessages = chatMessages.value;
  if (existingMessages.length > 0) {
    markMessagesAsRead();
  }
  
  scrollToBottom();
  wsService.setCurrentChat(conversationId);
  
  // 使用定义好的处理函数
  wsService.onMessage(handleNewMessage);

  // 添加页面可见性监听
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
  wsService.removeChat(conversationId);
  wsService.removeMessageListener(handleNewMessage);
});

// 监听新消息
watch(chatMessages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })
</script>

<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 修改为100vh，使其充满整个视口高度 */
  position: fixed; /* 添加固定定位 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff; /* 添加背景色 */
  z-index: 1000; /* 确保显示在最上层 */
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 添加此行以确保标题居中 */
  padding: 0 1rem;
  height: 60px; /* 修改高度为60px */
  background: #ffffff;
  border-bottom: 1px solid #ddd;
}

.back-button {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.chat-title {
  flex: 1; /* 添加此行以确保标题居中 */
  text-align: center; /* 添加此行以确保标题居中 */
  font-size: 1.2rem;
  font-weight: bold;
  color: black; /* 修改字体颜色为黑色 */
}

.chat-messages {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  background: #f5f5f5;
}

.message {
  margin-bottom: 1rem;
  padding: 0.5rem 1rem;
  border-radius: 10px;
  background: #ffffff;
  max-width: 70%;
}

.message.mine {
  align-self: flex-end;
  background: #dcf8c6;
}

.message-content {
  font-size: 1rem;
  color: #333;
}

.chat-input {
  display: flex;
  padding: 1rem;
  background: #ffffff;
  border-top: 1px solid #ddd;
}

.chat-input input {
  flex: 1;
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 20px;
  margin-right: 1rem;
}

.chat-input button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 20px;
  background: #3b82f6;
  color: #ffffff;
  cursor: pointer;
  transition: background 0.3s;
}

.chat-input button:hover {
  background: #2563eb;
}

.message-time {
  font-size: 0.8rem;
  color: #666;
  margin-top: 4px;
}
</style>